import { useRef, useState, useEffect, useImperativeHandle, forwardRef } from 'react';
import { createPortal } from 'react-dom';
import { cloneDeep } from 'lodash';
import { Button, Popup, NavBar, TextArea, List, Toast } from 'antd-mobile';
import MemberSelect from '@inbiz/basic/WapMemberSelect';
import { waphandleClick, moreClick, confirmed } from '../OutFunction';
import { InbizIcon, useEvents, h5Utils as Core, deepClone, getEditor, getSiteType } from '@inbiz/utils';
import { TextWidget, getMessage } from '@inbiz/react';
import extendsApi from '../api';
import { useDraft, useUrgeAndWithDraw } from '../useHooks';
import { filterBtns } from '../commonUtils';
import Tags from './Tags';
import { assignTask } from './service';
import './index.less';

interface ButtonStructure {
  action: string;
  name?: string;
  type?: string;
  styleType?: string;
  bgColor?: string;
  fontColor?: string;
  taskType?: string;
}

const IndexButton = forwardRef((props: any, ref) => {
  const { wapbuttonConfig, buttonVisible, tips, positionType, inbiz, radius } = props;
  const [hiddenButtons, $hiddenButtons] = useState(['']);
  const [visible, $visible] = useState(false);
  const [memberVisible, $memberVisible] = useState(false);
  const [assignVisible, setAssignVisible] = useState(false);
  const [defaultSelected, $defaultSelected] = useState<any[]>([]);
  const [selected, $selected] = useState<any[]>([]);
  const [buttons, $buttons] = useState({
    moreJudge: 0,
    displayButtons: wapbuttonConfig,
    manyButtons: [],
    theOtherButtons: [],
  });
  const [buttonLength, $buttonLength] = useState(wapbuttonConfig.length);
  const [clickedButton, $clickedButton] = useState<ButtonStructure>({
    action: '',
    name: '',
    type: '',
    styleType: '',
    bgColor: '',
    fontColor: '',
    taskType: '',
  });
  const processvars = useRef({});
  const mySummary = useRef('');
  // const processId = inbiz.queryData?.processId;
  const [opinions, $opinions] = useState('');
  const [processInstance, $processInstance] = useState('');
  const [isNewVersionDesigner, setIsNewVersionDesigner] = useState(inbiz?.workFlow?.newAttribute === true);
  const [newActions, setNewActions] = useState(inbiz?.workFlow?.newAttribute === true ? (inbiz?.workFlow?.buttonSetting?.actions || []).concat(inbiz?.workFlow?.buttonSetting?.returnsBackButtonConfig || []) : wapbuttonConfig);

  const { userInfoByToken: userInfo } = inbiz.appInfo;
  const [events] = useEvents(props.callBackEvents, props.emit);

  const isEditor = getEditor();

  const { taskType, taskId, instanceId, formId, id, pageId, tabKey, drafID, taskState, processId } =
    inbiz.queryData || {};
  const showDraft = useDraft({ processId, tabKey, isNewVersionDesigner });
  const { showIsUrge, showWithdraw } = useUrgeAndWithDraw({ processId, instanceId, tabKey, isNewVersionDesigner });

  useImperativeHandle(
    ref,
    () => ({
      ...extendsApi(events, mySummary, $hiddenButtons, processvars, $selected),
    }),
    [processvars, mySummary, hiddenButtons],
  );

  const hasSelect = (newButtons: any) => {
    let findStr = '';

    const moreLength = newButtons.findIndex((item: any) => {
      findStr = `${findStr}${getMessage(item.name)}`;
      return Core.getMojiLength(findStr) > 18;
    });
    return moreLength > -1 ? moreLength : newButtons.length;
  };

  useEffect(() => {
    if (inbiz?.workFlow?.ccMember || inbiz?.workFlow?.baseInfo?.ccMember) {
      if (isNewVersionDesigner) {
        const _ccMember = inbiz?.workFlow?.baseInfo?.ccMember ? JSON.parse(inbiz?.workFlow?.baseInfo?.ccMember) : [];
        const arr = _ccMember.map((item: { id: string; text: string }) => {
          return {
            id: item.id,
            name: item.text,
          }
        });
        $defaultSelected(arr);
      } else {
        const member = JSON.parse(inbiz?.workFlow.ccMember).map((item) => ({
          id: item.id,
          name: item.text,
        }));
        $defaultSelected(member);
      };
    };
  }, [inbiz?.workFlow, isNewVersionDesigner]);

  useEffect(() => {
    if (isEditor) {
      const btns = cloneDeep(isNewVersionDesigner ? newActions?.filter((item: { enable: boolean; }) => item?.enable !== false) : wapbuttonConfig);
      const moreJudge = hasSelect(btns);
      const manyButtons = btns.slice(0, moreJudge);
      const theOtherButtons = btns.slice(moreJudge);
      $buttons({
        moreJudge: moreJudge,
        displayButtons: btns,
        manyButtons,
        theOtherButtons,
      });
      $buttonLength(btns.length);
    } else {
      const btns = filterBtns({
        isNewVersionDesigner,
        buttons: isNewVersionDesigner ? newActions?.filter((item: { enable: boolean; }) => item?.enable !== false) : wapbuttonConfig,
        inbiz,
        tabKey,
        showDraft,
        showWithdraw,
        hiddenButtons,
        showIsUrge,
      });
      const moreJudge = hasSelect(btns);
      const manyButtons = btns.slice(0, moreJudge) as any;
      const theOtherButtons = btns.slice(moreJudge) as any;
      $buttons({
        moreJudge: moreJudge,
        displayButtons: btns,
        manyButtons,
        theOtherButtons,
      });
      $buttonLength(btns.length);
    }
  }, [
    wapbuttonConfig,
    showDraft,
    isEditor,
    tabKey,
    showWithdraw,
    showIsUrge,
    inbiz,
    hiddenButtons,
    isNewVersionDesigner,
  ]);

  // 接口成功回调
  const operationSuccess = (res: { code: string; isSuccess: boolean; context: string }, type: string, item) => {
    events.current.onAfterSubmit?.(item, res);
    // 计入缓存的最后一个地址
    const lastUrl = localStorage.getItem('lastUrl') as string;
    if (res.code == '200' || res.isSuccess) {
      Toast.show({
        icon: 'success',
        content: `${type}${getMessage('processButton.success')}`,
      });
      $visible(false);
      $opinions('');
      $processInstance('');
      if (window.timer) window.timer = null;
      window.timer = setTimeout(() => {
        if (getSiteType() == '1') {
          // window.history.back();
          window.location.replace(lastUrl);
        } else {
          window.close();
        }
        clearTimeout(window.timer);
      }, 500);
    } else {
      Toast.show({
        icon: 'fail',
        content: `${type}${getMessage('processButton.failure')}`,
      });
    }
    events.current.onBeforeClose?.(item?.action, res);
  };

  const buttonStyle = {
    height: 40,
    color: '#fff',
    background: '#1989fa',
    borderRadius: radius,
  };

  const selectedPerson = (selecteds: any) => {
    if (selecteds.length > 10) {
      Toast.show({
        icon: 'fail',
        content: getMessage('processButton.topsCCmember'),
      });
      return;
    }
    $selected(selecteds);
    $memberVisible(false);
  };

  const doAssign = (selecteds: any) => {
    if (selecteds.length < 1) {
      Toast.show({
        icon: 'fail',
        content: getMessage('processButton.chooseAssignPeople'),
      });
      return;
    };
    const params = {
      delegateUserId: selecteds.map((item) => item.id).join(','),
      handelUserId: userInfo.ID,
      taskIds: taskId,
    };
    inbiz?.submit?.(true).then(() => {
      assignTask(params).then((res) => {
        operationSuccess(res, getMessage('processButton.assign'), newActions?.find((item) => item?.action == 'assign'));
        setAssignVisible(false);
      });
    });
  };

  const removePeople = (item: { id: string }) => {
    const index = selected.findIndex((ele) => ele.id == item.id);
    const newSelected = deepClone(selected);
    newSelected.splice(index, 1);
    $selected(newSelected);
  };

  return (
    <div className={`processButton`} {...props}>
      {buttonVisible == 'visible' && (
        <>
          {buttonLength <= buttons.moreJudge && (
            <div className={'buttons'}>
              {buttons.displayButtons.map((item: ButtonStructure, index: number) => {
                return (
                  <Button
                    style={{
                      ...buttonStyle,
                      background:
                        item.bgColor && !item.bgColor.includes('undefined')
                          ? item.bgColor
                          : '#1989fa',
                      color:
                        item.fontColor && !item.fontColor.includes('undefined')
                          ? item.fontColor
                          : '#fff',
                    }}
                    // block={buttons.displayButtons.length <= 3 }
                    // block
                    key={index}
                    onClick={() => {
                      waphandleClick({
                        item,
                        events,
                        inbiz,
                        userInfo,
                        processId,
                        id,
                        formId,
                        drafID,
                        pageId,
                        operationSuccess,
                        $clickedButton,
                        $visible,
                        mySummary,
                        processvars,
                      })
                    }
                    }
                  >
                    <TextWidget>{item.name}</TextWidget>
                  </Button>
                );
              })}
            </div>
          )}

          {buttonLength > buttons.moreJudge && (
            <div className={'buttons'}>
              {buttons.manyButtons.map((item: ButtonStructure, index: number) => {
                if (item?.action == 'assign') {
                  return (
                    <Button
                      style={{
                        ...buttonStyle,
                        backgroundColor:
                          item.bgColor && !item.bgColor.includes('undefined')
                            ? item.bgColor
                            : '#1989fa',
                        color:
                          item.fontColor && !item.fontColor.includes('undefined')
                            ? item.fontColor
                            : '#fff',
                      }}
                      key={index}
                      // block
                      onClick={() => {
                        setAssignVisible(true);
                      }
                      }
                    >
                      <TextWidget>{item.name}</TextWidget>
                    </Button>
                  )
                } else {
                  return (
                    <Button
                      style={{
                        ...buttonStyle,
                        backgroundColor:
                          item.bgColor && !item.bgColor.includes('undefined')
                            ? item.bgColor
                            : '#1989fa',
                        color:
                          item.fontColor && !item.fontColor.includes('undefined')
                            ? item.fontColor
                            : '#fff',
                      }}
                      key={index}
                      // block
                      onClick={() => {
                        waphandleClick({
                          item,
                          events,
                          inbiz,
                          userInfo,
                          processId,
                          id,
                          formId,
                          drafID,
                          pageId,
                          operationSuccess,
                          $clickedButton,
                          $visible,
                          mySummary,
                          processvars,
                        })
                      }
                      }
                    >
                      <TextWidget>{item.name}</TextWidget>
                    </Button>
                  );
                }
              })}
              {taskType != 'faqishenqing' && (
                <Button
                  style={buttonStyle}
                  onClick={() => {
                    moreClick({ $clickedButton, $visible })
                  }}
                  key="more"
                >
                  <InbizIcon type="icon-more1" style={{ color: '#fff' }} />
                </Button>
              )}
            </div>
          )}
        </>
      )}
      {memberVisible
        ? createPortal(
          <div className={'popupMember'}>
            <MemberSelect
              onCancel={() => $memberVisible(false)}
              onOk={selectedPerson}
              multiple
              tabs={['user']}
              selected={selected}
            />
          </div>,
          document.body,
        )
        : null}
      {
        assignVisible
          ? createPortal(
            <div className={'popupMember'}>
              <MemberSelect
                onCancel={() => setAssignVisible(false)}
                onOk={doAssign}
                multiple
                tabs={['user']}
                selected={[]}
              />
            </div>,
            document.body,
          )
          : null
      }
      <Popup
        visible={visible}
        onMaskClick={() => {
          $opinions('');
          $selected([]);
          $visible(false);
        }}
        bodyStyle={{ height: 'auto' }}
      >
        {clickedButton.action !== 'more' && (
          <>
            <header className={'popupHeader'}>
              <NavBar
                onBack={() => {
                  $opinions('');
                  $selected([]);
                  $visible(false);
                }}
                backArrow={
                  <a>
                    <TextWidget>global.cancel</TextWidget>
                  </a>
                }
              >
                <TextWidget>{clickedButton.name}</TextWidget>
              </NavBar>
            </header>

            {/* 同意 拒绝*/}
            {(clickedButton.action == 'approve' || clickedButton.action == 'refuse') && (
              <>
                <section className={'popupBody'}>
                  <h4>
                    <TextWidget>processButton.comment</TextWidget>
                  </h4>
                  <TextArea
                    rows={5}
                    placeholder={getMessage(tips) || getMessage('processButton.tipsContent')}
                    onChange={(val) => $opinions(val)}
                    maxLength={163}
                  />
                </section>
                {taskState != 130 &&
                  !inbiz?.workFlow.ccMember && !inbiz?.workFlow?.baseInfo?.ccMember &&
                  inbiz?.workFlow?.activityNo !== 'sign' && (
                    <h4 className={'addRelatedPeople'} onClick={() => $memberVisible(true)}>
                      <InbizIcon
                        style={{ color: 'var(--inbiz-color-primary)', fontSize: 12 }}
                        type="icon-ic-add"
                      />{' '}
                      <span style={{ color: 'var(--inbiz-color-primary)', fontSize: 12 }}>
                        <TextWidget>processButton.addSendPeople</TextWidget>
                      </span>
                      {/**抄送人有另外的接口 */}
                    </h4>
                  )}
                <section>
                  <Tags
                    showValue={selected}
                    remove={removePeople}
                    ccMember={inbiz?.workFlow?.ccMember || inbiz?.workFlow?.baseInfo?.ccMember}
                    defaultSelected={defaultSelected}
                  />
                </section>
              </>
            )}
            {/* 退回上一步 退回发起人 退回发起人修改时显示 提交*/}
            {(clickedButton.action == 'returnsBack' ||
              clickedButton.action == 'returnsStarter' ||
              clickedButton.action == 'returnsStartModify' ||
              clickedButton.action == 'submit') && (
                <>
                  <section className={'popupBody'}>
                    <h4>
                      <TextWidget>processButton.comment</TextWidget>
                    </h4>
                    <TextArea
                      rows={5}
                      placeholder={getMessage(tips) || getMessage('processButton.tipsContent')}
                      onChange={(val) => $opinions(val)}
                      maxLength={163}
                    />
                  </section>
                </>
              )}

            {/* 前加签 后加签时显示 */}
            {(clickedButton.action == 'fowardPlusSign' ||
              clickedButton.action == 'backwardPlusSign') && (
                <>
                  <section className={'popupBody'}>
                    <h4>
                      <TextWidget>processButton.comment</TextWidget>
                    </h4>
                    <TextArea
                      rows={5}
                      placeholder={getMessage(tips) || getMessage('processButton.tipsContent')}
                      onChange={(val) => $opinions(val)}
                      maxLength={163}
                    />
                    {(inbiz?.workFlow?.plusSign || inbiz?.workFlow?.buttonSetting?.plusSign) && (
                      <h4 className={'addRelatedPeople'} onClick={() => $memberVisible(true)}>
                        <InbizIcon
                          style={{ color: 'var(--inbiz-color-primary)', fontSize: 12 }}
                          type="icon-ic-add"
                        />{' '}
                        <span style={{ color: 'var(--inbiz-color-primary)', fontSize: 12 }}>
                          <TextWidget>processButton.addPlusSignPeople</TextWidget>
                        </span>
                      </h4>
                    )}
                    <section>
                      <Tags showValue={selected} remove={removePeople} defaultSelected={[]} />
                    </section>
                  </section>
                </>
              )}

            {/* 撤回时显示 */}
            {clickedButton.action == 'withDraw' && (
              <>
                <section className={'popupBody'}>
                  <h4>
                    <TextWidget>processButton.inputcurrentInstance</TextWidget>(
                    {getMessage('processButton.mustInput')},{' '}
                    {getMessage('processButton.instanceNumber')}: {instanceId})
                  </h4>
                  <TextArea className={'cancelText'} rows={1} onChange={$processInstance} />
                  {/* <h4>审批意见</h4>
                  <TextArea
                    rows={5}
                    placeholder={tips || '请输入审批意见'}
                    onChange={(val) => $opinions(val)}
                  /> */}
                </section>
              </>
            )}

            {/* 终止时显示 */}
            {clickedButton.action == 'cancel' && (
              <>
                <section className={'popupBody'}>
                  <h4>
                    <TextWidget>processButton.inputcurrentInstance</TextWidget>
                    <TextWidget>processButton.toConfirmTerminate</TextWidget>(
                    {getMessage('processButton.mustInput')},{' '}
                    {getMessage('processButton.instanceNumber')}: {instanceId})
                  </h4>
                  <TextArea
                    className={'cancelText'}
                    rows={1}
                    placeholder={getMessage('processButton.cantBeUndone')}
                    onChange={$processInstance}
                  />
                  {tabKey != 7 && (
                    <>
                      <h4>
                        <TextWidget>processButton.comment</TextWidget>
                      </h4>
                      <TextArea
                        rows={5}
                        placeholder={getMessage(tips) || getMessage('processButton.tipsContent')}
                        onChange={(val) => $opinions(val)}
                        maxLength={163}
                      />
                    </>
                  )}
                </section>
              </>
            )}
            <footer className={'popoupFooter'}>
              <Button
                block
                style={{
                  height: 40,
                  backgroundColor: '#1989fa',
                  color: '#fff',
                  fontSize: 16,
                }}
                onClick={() => {
                  confirmed({
                    inbiz,
                    events,
                    clickedButton,
                    selected,
                    mySummary,
                    taskId,
                    opinions,
                    instanceId,
                    processvars,
                    taskState,
                    operationSuccess,
                    processInstance,
                    processId,
                    userInfo,
                    id,
                  })
                }
                }
              >
                <TextWidget>processButton.confirmText</TextWidget>
              </Button>
            </footer>
          </>
        )}

        {clickedButton.action == 'more' && (
          <>
            <header className={'popupHeader'}>
              <NavBar
                onBack={() => $visible(false)}
                backArrow={
                  <a>
                    <TextWidget>global.cancel</TextWidget>
                  </a>
                }
              >
                <TextWidget>{clickedButton.name}</TextWidget>
              </NavBar>
            </header>
            <section className={'popupBody'}>
              <List>
                {buttons.theOtherButtons.map((item: ButtonStructure, index: number) => {
                  return (
                    <List.Item
                      onClick={() => {
                        waphandleClick({
                          item,
                          events,
                          inbiz,
                          userInfo,
                          processId,
                          id,
                          formId,
                          drafID,
                          pageId,
                          operationSuccess,
                          $clickedButton,
                          $visible,
                          mySummary,
                          processvars,
                        })
                      }

                      }
                      arrow={false}
                      key={index}
                    >
                      <TextWidget>{item.name}</TextWidget>
                    </List.Item>
                  );
                })}
              </List>
            </section>
          </>
        )}
      </Popup>
    </div>
  );
});

export default IndexButton;
